package ar.com.spsolutions.splibrary.dashboard;

import java.util.HashSet;
import java.util.Set;

import org.joda.time.DateTime;
import org.joda.time.LocalDate;

import ar.com.spsolutions.splibrary.book.LoanBook;
import ar.com.spsolutions.splibrary.notifiers.INotifier;
import ar.com.spsolutions.splibrary.user.User;
import ar.com.spsolutions.splibrary.utils.DateUtil;

public class DashBoard {

    private Set<User> users;

    private INotifier notifier;

    public DashBoard(final Set<User> usersSet, final INotifier aNotifier) {
        users = usersSet;
        notifier = aNotifier;
    }

    public DashBoard() {
        // javabean
    }

    public Set<LoanBook> getLoansDues() {
        Set<LoanBook> rents = new HashSet<LoanBook>();
        for (User user : getUsers()) {
            if (user.hasRentsDue()) {
                rents.addAll(user.getLoansDue());
            }
        }
        return rents;
    }

    public void notifyDues() {
        Set<LoanBook> dues = getLoansDues();
        String mailSubject = "Prestamo vencido";
        for (LoanBook rentBook : dues) {

            DateTime stimated = rentBook.getRefundDate().plusDays(4);
            LocalDate laboralDate = DateUtil.getLaboralDate(stimated.toLocalDate());
            DateTime date = DateUtil.toDateTime(laboralDate);

            // chequeo que haya 4 dias de deuda
            if (date.equals(DateTime.now())) {

                String mailMessage = String.format(
                        "El prestamo del libro %s vencio el %s, por tal motivo de envia este mail",
                        rentBook.bookTitle(), rentBook.getRefundDate());
                User user = rentBook.getUser();
                getNotifier().setRecipient(user);
                getNotifier().setSubject(mailSubject);
                getNotifier().setMessage(mailMessage);
                getNotifier().sendNotification();
            }
        }

    }

    // ---accessors---
    public Set<User> getUsers() {
        return users;
    }

    public void setUsers(final Set<User> users) {
        this.users = users;
    }

    public INotifier getNotifier() {
        return notifier;
    }

    public void setNotifier(final INotifier notifier) {
        this.notifier = notifier;
    }

}
